<?php
namespace Core\CoreCommons;

/*
* Localization class definition. This class allow to use different culture on the web site. It's use xml file in order to provide translations.
*
* @method Localization Singleton()
*/
class Localization 
{
	/*
	* @property array $Keys This an array which contains all translations
	*/
	public static $Keys;
	
	/*
	* @property Localization $instance An instance of localization
	*/
	private static $instance;
	
	/*
	* Singleton pattern
	*/
	public static function Singleton() 
	{
		if (!isset(self::$instance)) {
			$c = __CLASS__;
			self::$instance = new $c;
		}
		return self::$instance;
	}	
	
	/*
	* Default constructor
	*/
	private function __construct() 
	{
		self::UpdateTranslationsList();
	}
	
	/*
	* Get the translation by key
	*	
	* @param string $key Get the translation by key
	*
	* @return string The translation
	*/
	public static function Get($key)
	{
		Logger::Info("get $key translation");
		
		if(isset(self::$Keys) == false || count(self::$Keys) == 0)
		{
			self::UpdateTranslationsList();
		}
		
		$response = (string)$key;
		
		if(!isset(self::$Keys->$key))
		{
			$response = "### ". (string)$key ." ###";
			Logger::Warning("Missing translation : " . $key);
		}
		else
		{
			$response = (string)self::$Keys->$key;
		}
		
		return (string)$response;
	}
	
	/*
	* Get all translations
	*
	* @return array The array which contains all translations in Keys property
	*/
	public function GetTranslations()
	{
		Logger::Info("get all translations");
		
		return self::$Keys;
	}
	
	/*
	* This method fill the translations list
	*
	* @return boolean The response is true if is filled
	*/
	private static function UpdateTranslationsList()
	{
		try
		{
			Logger::Info("Start to update translations");
		
			self::$Keys = array();
			
			$parameters = Parameters::Singleton();
			
			Logger::Info("Loading " .  $parameters::Get('culture') . " culture.");
			
			$file = CORE_DIR . "../GUI/assets/lang/". $parameters::Get("culture") .".json";
			
			if(!file_exists($file))
			{
				throw new \Exception("The translation file $file doesn't exist.");
			}
			
			$str = file_get_contents($file);
			$json = json_decode($str); 
			self::$Keys = $json;
		}
		catch(\Exception $ex)
		{
			Logger::Error("localization.UpdateTranslationsList " . $ex->getMessage());
		}
	}
}

?> 